import gc,time
import machine
import network
import machine
import uos
from machine import UART,Pin
uart0 = UART(1, baudrate=57600, tx=3, rx=2)
OUT = Pin(12, Pin.IN) # 输出 #右边指示灯
# 定义一个全局变量来记录开机次数
boot_count = 0

try:
    # 尝试从非易失性存储中读取开机次数
    with open('boot_count.txt', 'r') as f:
        boot_count = int(f.read())
except:
    # 如果文件不存在，说明是第一次开机
    pass

def connect_wlan(ssid, password):
    gc.collect()
    station = network.WLAN(network.STA_IF)
    ap_if = network.WLAN(network.AP_IF)
    station.active(True)
    ap_if.active(False)

    if not station.isconnected():
        print("Connecting to WLAN ({})...".format(ssid))
        station.active(True)
        station.connect(ssid, password)
    if station.isconnected():
        print(station.ifconfig())

    return True



def OTA():
    try:
        gc.collect()
        M=[0X55,0Xaa,0X02,0X58,0X58,0X58,0X00,0Xb8,0X22,0Xb8,0X22,0Xb8,0X22,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00]
        sum=0
        for i in range(0,len(M)):
            sum+=M[i]
        sum=sum & 0xff
        M.append(sum)
        #         print(M)
        uart0.write(bytes(M))  # write 5 bytes
        print("连接wifi")
        station = network.WLAN(network.STA_IF)
        ap_if = network.WLAN(network.AP_IF)
        station.active(True)
        ap_if.active(False)

        if not station.isconnected():
            print("Connecting to WLAN ({})...".format("Sensen"))
            station.active(True)
            station.connect("15367660966", "15367660")
        while not station.isconnected():
                pass    
        print(station.ifconfig())
        import senko
        OTA = senko.Senko(user="zhong-weisen", repo="ESP32", working_dir="esp32_Ktdy/", files=["ktdy.py"])
#         https://gitee.com/zhong-weisen/ESP32/raw/master/esp32_Ktdy/ktdy.py
        if OTA.update():
            print("更新成功")
            machine.reset()
        gc.collect()    
    except Exception as e:
        print("更新失败",e)


if __name__ == "__main__":
        if boot_count == 1 or OUT.value() == 1 :
            print("开始更新")
            OTA()
        print("启动程序")
        from ktdy import*  
        loop()

    



